<template>
  <div class="idiom">
    <van-nav-bar title="成语游戏" left-text="" left-arrow @click-left="back" />

    <div v-if="state.problem && state.problem.title" class="problem">
      <div class="title alimama-dong-fang">
        {{ state.problem.title }}
      </div>
      <!-- {{ state.time }} -->
      <div class="timer">
        <template v-if="progress.speed">
          <van-circle
            v-model:current-rate="progress.current" :text="state.time.toString()" :rate="0"
            :speed="progress.speed" layer-color="#EACAB7" color="#E6876F" fill="#EACAB7" start-position="bottom"
            size="44"
          />
        </template>
      </div>
      <div class="description">
        {{ state.problem.questionName }}
      </div>
      <div class="options">
        <div
          v-for="item in state.problem.answers" :key="item.guid" class="option" :class="{
            sucess: item.isAnswer && state.showAnswer,
            error: !item.isAnswer && state.showAnswer,
          }" @click="state.answer ? '' : selectOption(item.id)"
        >
          <span>{{ item.answerDesc }}</span>
          <span v-show="state.showAnswer && state.answer === item.id">
            <img
              v-if="item.isAnswer" src="https://jwc-static.jdwxk.com/imgs/activities/problem_res_right.png" alt=""
              srcset=""
            >
            <img v-else src="https://jwc-static.jdwxk.com/imgs/activities/problem_res_error.png" alt="" srcset="">
          </span>
        </div>
      </div>
    </div>
  </div>

  <ResultTip ref="ResultTipRef" />
</template>

<script setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import ResultTip from './resultTip/index.vue'
import { cardAdd, questionPage, scoreAdd } from '@/api/activities'
import { useUserStoreWidthOut } from '@/store/modules/user'

const userStore = useUserStoreWidthOut()
const userInfo = computed(() => userStore.getUserInfo)

const route = useRoute()
const router = useRouter()
function back() {
  router.back()
}

const state = reactive({
  key: '',
  problemLibrary: [],
  problem: null,
  time: 30,
  answer: '',
  showAnswer: false,
})

const progress = reactive({
  speed: null,
  current: 100,
  timer: null,
})

const ResultTipRef = ref()
async function openResultTip() {
  if (state.answer === -1) {
    const a = {
      isRight: false,
      message: '很遗憾，您答题已超时', // 答案正确但是加分异常
    }
    ResultTipRef.value.open(a)
  }
  else {
    const answerItem = state.problem.answers.filter((i) => {
      return i.id === state.answer
    })[0]
    let responseScore
    let responseCard
    if (answerItem.isAnswer === 1) {
      responseScore = await scoreAdd({
        phone: userInfo.value.phone,
        // phone: '18638324792',
        projectName: '',
        eventDesc: new Date().toLocaleString(),
        activityType: '1',
        questionId: state.problem.id,
        typeDesc: null,
      })
      console.log('scoreAdd', responseScore)
      responseCard = await cardAdd({
        phone: userInfo.value.phone,
        // phone: '18638324792',
        picId: state.problem.configPic.id,
        source: '扫码',
      })
      console.log('cardAdd', responseCard)
    }
    let message = ''
    if (answerItem.isAnswer === 1) {
      // if (responseScore.code === 200) {
      //   message += responseScore.data
      // }
      // if (responseCard.code === 200) {
      //   message += responseCard.data
      // }
      if (responseScore.code === 200 && responseCard.code === 201) {
        message = `恭喜您，获得 10 积分`
      }
      else if (responseScore.code === 201 && responseCard.code === 200) {
        message = `恭喜您，获得 卡片`
      }
      else if (responseScore.code === 200 && responseCard.code === 200) {
        message = `恭喜您，获得卡片与 10 积分`
      }
      else {
        message = `您已获得该卡片`
      }
    }
    else {
      message = answerItem.message
      state.problem.configPic.pic = ''
    }
    const a = {
      isRight: answerItem.isAnswer === 1,
      message, // 答案正确但是加分异常
      cardPic: state.problem.configPic.pic,
    }
    console.log('提示', a)

    ResultTipRef.value.open(a)
  }
}

function startGame() {
  progress.speed = 100 / state.time
  progress.timer = setInterval(() => {
    if (state.time > 0) {
      state.time -= 1
      // 测试警告触发原因
      // progress.current -= progress.speed
    }
    else {
      clearInterval(progress.timer)
      if (state.answer === '') {
        state.answer = -1
        // popShow.value = true3

        openResultTip()
      }
    }
  }, 1000)
}
function endGame() {
  clearInterval(progress.timer)
}

// function close() {
//   popShow.value = false
// }
function selectOption(id) {
  // 暂时只考虑单选,如果多选再做变更
  state.answer = id
  state.showAnswer = true
  openResultTip()
}

async function getProblem() {
  const res = await questionPage(userInfo.value.phone)
  if (res.code === 200) {
    state.problemLibrary = res.data.records
    const matchRes = state.problemLibrary.filter((i) => {
      return i.title === state.key
    })
    state.problem = matchRes.length > 0 ? matchRes[0] : state.problemLibrary[0]
    // console.log("state.problem", state.problem);
  }
}

onMounted(async () => {
  // console.log("router.query", route.query);
  state.key = route.query.key
  // state.key = router.para
  await userStore.GetUserInfo()
  await getProblem()
  startGame()
})
onUnmounted(() => {
  endGame()
})
</script>

<style lang="scss">
.idiom {
  background: url('https://jwc-static.jdwxk.com/imgs/activities/idiom_bg.png');
  background-size: cover;
  height: 100vh;
  width: 100%;
  background-repeat: no-repeat;
  position: relative;

  .van-circle__text {
    font-size: 20;
    color: #d5674b;
  }

  .problem {
    width: 344px;
    // height: 610px;
    height: calc(100vh - 76.3px - 60px);
    position: absolute;
    transform: translate(-50%, -50%);
    left: 50%;
    top: calc(50% + 25px);
    background: url('https://jwc-static.jdwxk.com/imgs/activities/content_bg.png');
    background-size: 100% 100%;
    background-repeat: no-repeat;
  }

  .title {
    width: 229px;
    height: 55px;
    transform: translate(0, -50%);
    background: url('https://jwc-static.jdwxk.com/imgs/activities/idiom_title_bg.png');
    background-size: contain;
    background-repeat: no-repeat;
    background-position: center;
    text-align: center;
    line-height: 55px;
    color: #e09661;
    font-size: 18px;
  }

  .timer {
    margin-top: -10px;
    margin-bottom: -10px;
  }

  .problem {
    display: flex;
    align-items: center;
    flex-direction: column;
  }

  .description {
    margin-top: 16px;
    width: 282px;
    text-align: justify;
    font-size: 16px;
    line-height: 27.5px;
    min-height: 80px;
    max-height: 300px;
    height: calc(100vh - 76.3px - 60px - 280px);
    overflow-y: scroll;
    color: #333333;
  }

  .options {
    display: flex;
    align-items: center;
    flex-direction: column;
    gap: 20px;
    margin-top: 20px;
    // height: 180px;
  }

  .option {
    background: #d5c3a5;
    border-radius: 6px;
    width: 256px;
    // height: 44px;
    // line-height: 44px;
    padding: 10px 22px;
    color: white;

    display: flex;
    align-items: center;
    justify-content: space-between;

    & > span:first-child {
      flex-grow: 1;
    }

    & > span:last-child {
      flex-shrink: 0;
      width: 21px;
      height: 21px;

      img {
        width: 100%;
        height: 100%;
      }
    }
  }

  .option.sucess {
    background: linear-gradient(to right, #4b965b, #82c66f);
  }

  .option.error {
    background: linear-gradient(to right, #bc3333, #d3503e);
  }
}

.result_overlay {
  z-index: 10;

  .result_wrapper {
    position: fixed;
    z-index: 11;
    transform: translate(-50%, -50%);
    left: 50%;
    top: 50%;

    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
  }

  .content {
    width: 326px;
    height: 290px;
    border-radius: 12px;
    border: 2.5px solid #b67565;
    background: white;
    position: relative;
    padding: 36px;

    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;

    .answer_right_icon {
      width: 156px;
      height: 99px;
    }

    .answer_error_icon {
      width: 148px;
      height: 72px;
    }

    .text {
      color: #663c2a;
      font-size: 15px;
      line-height: 25.5px;
      font-weight: 700;
      text-align: center;
    }

    .readOver_btn {
      width: 144px;
      height: 34px;
      background: #c19760;
      border-radius: 30px;
      color: white;
    }
  }

  .close_btn {
    width: 58.5px;
    height: 58.5px;
    border-radius: 58.5px;
    border: 2.5px solid white;
    margin-top: 20px;
    display: flex;
    align-content: center;
    justify-content: center;

    .close_icon {
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
</style>
